import {useHistory} from 'react-router-dom'
import {NavBar} from 'antd-mobile'
import styles from './index.module.scss'
import useSearch from "@/utils/useSearch";
import {getSearchResult} from "@/store/actions/search";
import useInitState from "@/utils/useInitState";
import ArticleItem from "@/pages/Home/components/ArticleItem";

/**
 * 当前项目数据存储全部使用redux
 * 根据用户输入关键字获取搜索结果
 * thunk ==> 获取搜索的结果
 * 获取到的搜索结果，放到store里面
 * 界面想要渲染直接从useSelector里面取出数据，渲染即可
 */

const Result = () => {
  const history = useHistory()
  // 传入的参数：需要获取的参数的key
  const [q] = useSearch('q')
  const {searchResults: {results}} = useInitState(() => getSearchResult(q), 'search')
  // console.log(results)
  const renderArticleList = () => {
    return results.map((item, index) => {
      const {
        title,
        pubdate,
        comm_count,
        aut_name,
        cover: {type, images},
        art_id
      } = item

      //  把数据进行组合
      const articleData = {
        title,
        pubdate,
        comm_count,
        aut_name,
        type,
        images
      }

      return <div onClick={() => history.push(`/article/${art_id}`)} key={index} className={'article-item'}>
        <ArticleItem {...articleData} />
      </div>
    })
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {renderArticleList()}
      </div>
    </div>
  )
}

export default Result
